<script setup lang="ts">
import * as RedPacketConfigApi from '@/api/promotion/redpacket/RedPacketConfigApi'
import { fenToYuan, yuanToFen } from '@/utils'
import { formatDate, formatTime } from '@/utils/formatTime'
import { checkRole } from '@/utils/permission'

const ymd = formatDate(new Date(), 'YYYY-MM-DD')

const formData = ref<any>({
  id: undefined,
  featureEnable: true,
  firstAmount: 0,
  continueMode: 0,
  continueAmount: 0,
  continueThresholdPrice: 0,
  continueGrantScene: 0,
  continueGrantStartTime: '',
  continueGrantEndTime: '',
  delayEffectHours: 0,
  validationDays: 0,
  note: ''
})
const formRules = reactive({
  featureEnable: [{ required: true, message: '功能开关不能为空', trigger: 'blur' }],
  firstAmount: [{ required: true, message: '新客红包金额不能为空', trigger: 'blur' }],
  continueMode: [{ required: true, message: '请选择消费红包发放模式', trigger: 'blur' }],
  continueAmount: [
    {
      message: '请输入消费红包金额',
      trigger: ['blur', 'change'],
      validator: (_rule: any, value: any, callback: any) => {
        const n = parseFloat(value)
        if (formData.value.continueMode === 0 && (isNaN(n) || n < 0)) {
          callback(new Error('按固定金额发放红包时必须填写红包金额'))
        } else {
          callback()
        }
      }
    }
  ],
  continueThresholdPrice: [{ required: true, message: '消费门槛金额不能为空', trigger: 'blur' }],
  continueGrantScene: [{ required: true, message: '请选择发放场景', trigger: 'blur' }],
  delayEffectHours: [{ required: true, message: '红包延迟生效小时数不能为空', trigger: 'blur' }],
  validationDays: [{ required: true, message: '红包有效天数不能为空', trigger: 'blur' }]
})
const formRef = ref()

const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      RedPacketConfigApi.write(formData.value)
    }
  })
}

const computedFirstAmount = computed({
  get: () => {
    return Number(fenToYuan(formData.value.firstAmount))
  },
  set: (value) => {
    formData.value.firstAmount = yuanToFen(value)
  }
})
const computedContinueAmount = computed({
  get: () => {
    return Number(fenToYuan(formData.value.continueAmount))
  },
  set: (value) => {
    formData.value.continueAmount = yuanToFen(value)
  }
})
const computedContinueThresholdPrice = computed({
  get: () => {
    return Number(fenToYuan(formData.value.continueThresholdPrice))
  },
  set: (value) => {
    formData.value.continueThresholdPrice = yuanToFen(value)
  }
})
const computedContinueGrantTimeRange = computed({
  get: () => {
    return [formData.value.continueGrantStartTime, formData.value.continueGrantEndTime]
  },
  set: (value) => {
    if (value.length !== 2) {
      return
    }
    formData.value.continueGrantStartTime = ymd + ' ' + formatTime(value[0])
    formData.value.continueGrantEndTime = ymd + ' ' + formatTime(value[1])
  }
})

const onContinueModeChange = async (mode?: string | number | boolean): any => {
  // 切换发放模式时的处理
  if (mode === 1) {
    // 切换到按消费金额发放时，清空固定金额
    formData.value.continueAmount = 0
  }
  // 重新验证表单
  await formRef.value.validateField('continueAmount')
}

const formLoading = ref(false)
const loadConfig = async () => {
  formLoading.value = true
  try {
    formData.value = await RedPacketConfigApi.read()
  } finally {
    formLoading.value = false
  }
}
onMounted(async () => {
  if (checkRole(['shop_admin'])) {
    await loadConfig()
    return
  }
})
</script>

<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="110px"
    v-loading="formLoading"
  >
    <el-form-item label="功能开关" prop="featureEnable">
      <div class="flex flex-col">
        <el-switch
          v-model="formData.featureEnable"
          :active-value="true"
          :inactive-value="false"
          active-text="开启"
          inactive-text="关闭"
          inline-prompt
        />
        <el-text v-if="formData.featureEnable" type="info">
          功能关闭后将不会发放红包及使用红包抵扣。
        </el-text>
        <el-text v-else type="info">功能开启后才支持发放红包及使用红包抵扣。</el-text>
      </div>
    </el-form-item>
    <el-form-item label="新客红包" prop="firstAmount">
      <div class="flex flex-col">
        <el-input-number
          v-model="computedFirstAmount"
          :min="0"
          :step="1"
          :precision="2"
          clearable
          placeholder="红包金额"
          class="!w-240px"
        >
          <template #prefix>发放</template>
          <template #suffix>元</template>
        </el-input-number>
        <el-text type="info"
          >用户只要还未在店铺消费过都会发放一个新客红包。【注意】开启了首单优惠功能的情况下不建议再发放新客红包。</el-text
        >
      </div>
    </el-form-item>
    <el-form-item label="发放模式" prop="continueMode">
      <el-radio-group v-model="formData.continueMode" @change="onContinueModeChange">
        <el-radio :value="0">按固定金额发放</el-radio>
        <el-radio :value="1">按消费金额发放</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData.continueMode === 0" label="红包金额" prop="continueAmount">
      <div class="flex flex-col">
        <el-input-number
          v-model="computedContinueAmount"
          :min="0"
          :step="1"
          :precision="2"
          clearable
          placeholder="红包金额"
          class="!w-240px"
        >
          <template #prefix>发放</template>
          <template #suffix>元</template>
        </el-input-number>
        <el-text type="info">用户每次在店铺消费后都会发放一个消费红包。</el-text>
      </div>
    </el-form-item>
    <el-form-item label="发放门槛" prop="continueThresholdPrice">
      <div class="flex flex-col">
        <el-input-number
          v-model="computedContinueThresholdPrice"
          :min="0"
          :step="1"
          :precision="2"
          placeholder="门槛金额"
          clearable
          class="!w-240px"
        >
          <template #prefix>消费满</template>
          <template #suffix>元</template>
        </el-input-number>
        <el-text type="info">用户每次在店铺消费达到指定门槛金额后都会发放一个消费红包。 </el-text>
      </div>
    </el-form-item>
    <el-form-item label="发放场景" prop="continueGrantScene">
      <div>
        <el-radio-group v-model="formData.continueGrantScene">
          <el-radio :value="1">扫码收款时发放</el-radio>
          <el-radio :value="2">在线购物时发放</el-radio>
          <el-radio :value="0">扫码收款及在线购物时发放</el-radio>
        </el-radio-group>
        <br />
        <el-text v-if="formData.continueGrantScene === 1" type="info">
          用户每次扫商家收款码码付款后会发放一个消费红包。
        </el-text>
        <el-text v-else-if="formData.continueGrantScene === 2" type="info">
          用户每次在商家店铺里在线购物后会发放一个消费红包。
        </el-text>
        <el-text v-else type="info">
          用户每次扫商家收款码码付款及在商家店铺里在线购物后会发放一个消费红包。
        </el-text>
      </div>
    </el-form-item>
    <el-form-item label="发放时段" prop="continueGrantTimeRange">
      <div>
        <el-time-picker
          v-model="computedContinueGrantTimeRange"
          is-range
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="HH:mm:ss"
        />
      </div>
    </el-form-item>
    <el-form-item label="生效时间" prop="delayEffectHours">
      <div class="flex flex-col">
        <el-input-number
          v-model="formData.delayEffectHours"
          :min="0"
          clearable
          placeholder="小时数"
          class="!w-240px"
        >
          <template #prefix>发放</template>
          <template #suffix>小时后生效</template>
        </el-input-number>
        <el-text type="info">0表示红包发放后马上生效，大于0表示延时生效。</el-text>
      </div>
    </el-form-item>
    <el-form-item label="失效时间" prop="validationDays">
      <div class="flex flex-col">
        <el-input-number
          v-model="formData.validationDays"
          :min="1"
          clearable
          placeholder="天数"
          class="!w-240px"
        >
          <template #prefix>发放</template>
          <template #suffix>天后失效</template>
        </el-input-number>
        <el-text type="info">红包发放后用户只能在规定的有效期内使用。</el-text>
      </div>
    </el-form-item>
    <el-form-item label="规则说明" prop="note">
      <editor v-model="formData.note" mode="simple" height="150px" placeholder="请输入规则说明" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm" :loading="formLoading">保 存</el-button>
    </el-form-item>
  </el-form>
</template>
